package C054;

/**
 * ClassName: C02
 * Package: C054
 * Description:
 *
 * @Author BCXJ
 * @Create 2025/3/30 10:11
 * @Version 1.0
 * @Since 1.0
 */
public class C02 {
    public static void main(String[] args) {
        //int[] arr = {4, 2, 2, 2, 4, 4, 2, 2};
        int[] arr = {0,6};
        //int[] arr = {8,2,4,7};
        System.out.println(longestSubarray(arr, 5));
    }

    static int maxh, maxt, minh, mint;
    static int MAXLEN = 100001;
    static int[] maxQueue = new int[MAXLEN];
    static int[] minQueue = new int[MAXLEN];

    public static int longestSubarray(int[] nums, int limit) {
        maxh = maxt = minh = mint = 0;
        int ans = 0;
        for (int l = 0, r = 0; l < nums.length;l++) {
            // 是否满足
            while(r < nums.length && ok(nums, limit, nums[r])) {
                push(nums, r++);
            }
            System.out.println(l + " " + (r-1));
            ans = Math.max(ans, r - l);
            // 弹出元素
            pop(l);
        }
        return ans;
    }

    private static void pop(int l) {
        if (maxh < maxt && l == maxQueue[maxh]) {
            maxh++;
        }
        if (minh < mint && l == minQueue[minh]) {
            minh++;
        }
    }

    private static boolean ok(int[] nums, int limit, int number) {
        int min = (minh < mint) ? Math.min(nums[minQueue[minh]], number) : limit;
        int max = (maxh < maxt) ? Math.max(nums[maxQueue[maxh]], number) : limit;
        //System.out.println(min + " " + max);
        return max - min <= limit;
    }


    // 单调队列加入元素
    private static void push(int[] nums, int r) {
        while (maxh < maxt && nums[r] >= nums[maxQueue[maxt - 1]]) {
            maxt--;
        }
        maxQueue[maxt++] = r;
        while (minh < mint && nums[r] <= nums[minQueue[mint - 1]]) {
            mint--;
        }
        minQueue[mint++] = r;
    }
}
